package cn.jlonely.xyhx.app.service.impl;


import cn.jlonely.xyhx.app.mapper.UseMapper;
import cn.jlonely.xyhx.app.service.UseService;
import cn.jlonely.xyhx.pojo.User;
import cn.jlonely.xyhx.pojo.vo.AppUserVo;
import cn.jlonely.xyhx.pojo.vo.UserVo;
import cn.jlonely.xyhx.utils.JwtUtils;
import cn.jlonely.xyhx.utils.SHA256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UseServiceImpl implements UseService {

    @Autowired
    private UseMapper useMapper;

    @Override
    public User login(UserVo userVo) throws Exception {
        // 对输入的密码进行加密
        String encryptedPassword = SHA256Util.sha256(userVo.getPassword());
        // 设置加密后的密码到 Admin 对象中
        userVo.setPassword(encryptedPassword);

        User user = useMapper.selectByUsernameAndPassword(userVo);
        //生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        try {
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
        }catch (Exception e){
            return null;
        }
        String jwt =  JwtUtils.generateJwt(claims);

        // 将 JWT 设置到 User 对象中
        user.setToken(jwt);

        return user;
    }

    /**
     * 注册
     * @param user
     */
    @Override
    public void register(AppUserVo user) throws Exception {
        boolean notUsername = useMapper.selectByUsername(user.getUsername()); // 检查用户名是否存在
        if (!notUsername) {
            throw new Exception("用户名已存在");
        }
        user.setPassword(SHA256Util.sha256(user.getPassword()));
        useMapper.register(user);
    }

    /**
     * 用户修改信息
     * @param appUserVo
     */
    @Override
    public void update(AppUserVo appUserVo) {
        useMapper.update(appUserVo);
    }

}
